<template>
  <canvas ref="canvasRef" class="particle-nebula"></canvas>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const canvasRef = ref(null)
let animationId = null

onMounted(() => {
  const canvas = canvasRef.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  
  // 设置canvas尺寸
  const resizeCanvas = () => {
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
  }
  resizeCanvas()
  window.addEventListener('resize', () => {
    resizeCanvas()
    initTargetPositions()
  })
  
  // 鼠标位置和力场
  const mouse = { x: 0, y: 0, active: false }
  const handleMouseMove = (e) => {
    mouse.x = e.clientX
    mouse.y = e.clientY
    mouse.active = true
  }
  const handleMouseLeave = () => {
    mouse.active = false
  }
  window.addEventListener('mousemove', handleMouseMove)
  window.addEventListener('mouseleave', handleMouseLeave)
  
  // "1024" 文字的目标位置
  let targetPositions = []
  
  const initTargetPositions = () => {
    targetPositions = []
    
    // 在离屏canvas上绘制"1024"文字
    const textCanvas = document.createElement('canvas')
    const textCtx = textCanvas.getContext('2d')
    
    const fontSize = Math.min(canvas.width * 0.3, 200)
    textCanvas.width = canvas.width
    textCanvas.height = canvas.height
    
    textCtx.font = `bold ${fontSize}px Arial, sans-serif`
    textCtx.fillStyle = 'white'
    textCtx.textAlign = 'center'
    textCtx.textBaseline = 'middle'
    textCtx.fillText('1024', canvas.width / 2, canvas.height / 2)
    
    // 采样像素点作为目标位置（优化：增加间隔减少采样点）
    const imageData = textCtx.getImageData(0, 0, textCanvas.width, textCanvas.height)
    const isMobile = /mobile|android|iphone|ipad/i.test(navigator.userAgent)
    const gap = isMobile ? 6 : 5 // 移动端更大间隔
    
    for (let y = 0; y < textCanvas.height; y += gap) {
      for (let x = 0; x < textCanvas.width; x += gap) {
        const index = (y * textCanvas.width + x) * 4
        const alpha = imageData.data[index + 3]
        
        if (alpha > 128) {
          targetPositions.push({ x, y })
        }
      }
    }
  }
  
  // 粒子类
  class Particle {
    constructor(targetPos) {
      this.targetX = targetPos.x
      this.targetY = targetPos.y
      
      // 随机初始位置
      this.x = Math.random() * canvas.width
      this.y = Math.random() * canvas.height
      
      this.vx = 0
      this.vy = 0
      this.size = 1 + Math.random() * 2
      
      // 随机颜色
      const colors = [
        { r: 99, g: 102, b: 241 },   // 蓝
        { r: 139, g: 92, b: 246 },   // 紫
        { r: 236, g: 72, b: 153 },   // 粉
        { r: 0, g: 243, b: 255 },    // 霓虹蓝
      ]
      this.color = colors[Math.floor(Math.random() * colors.length)]
    }
    
    update() {
      // 力1：向目标位置移动
      const dx = this.targetX - this.x
      const dy = this.targetY - this.y
      const distToTarget = Math.sqrt(dx * dx + dy * dy)
      
      const attractionForce = 0.05
      this.vx += dx * attractionForce
      this.vy += dy * attractionForce
      
      // 力2：鼠标力场（吸引或排斥）
      if (mouse.active) {
        const mdx = mouse.x - this.x
        const mdy = mouse.y - this.y
        const distToMouse = Math.sqrt(mdx * mdx + mdy * mdy)
        
        if (distToMouse < 200) {
          const mouseForce = (200 - distToMouse) / 200 * 2
          // 排斥力
          this.vx -= (mdx / distToMouse) * mouseForce
          this.vy -= (mdy / distToMouse) * mouseForce
        }
      }
      
      // 力3：随机扰动
      this.vx += (Math.random() - 0.5) * 0.2
      this.vy += (Math.random() - 0.5) * 0.2
      
      // 阻尼
      this.vx *= 0.9
      this.vy *= 0.9
      
      // 更新位置
      this.x += this.vx
      this.y += this.vy
      
      // 边界检查
      if (this.x < 0) this.x = 0
      if (this.x > canvas.width) this.x = canvas.width
      if (this.y < 0) this.y = 0
      if (this.y > canvas.height) this.y = canvas.height
    }
    
    draw(ctx) {
      // 根据距离目标的远近调整透明度
      const dx = this.targetX - this.x
      const dy = this.targetY - this.y
      const dist = Math.sqrt(dx * dx + dy * dy)
      const alpha = Math.max(0.3, 1 - dist / 200)
      
      ctx.fillStyle = `rgba(${this.color.r}, ${this.color.g}, ${this.color.b}, ${alpha})`
      ctx.shadowBlur = 5
      ctx.shadowColor = `rgb(${this.color.r}, ${this.color.g}, ${this.color.b})`
      
      ctx.beginPath()
      ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2)
      ctx.fill()
    }
    
    // 绘制连线
    drawConnection(ctx, other) {
      const dx = other.x - this.x
      const dy = other.y - this.y
      const dist = Math.sqrt(dx * dx + dy * dy)
      
      if (dist < 80) {
        const alpha = (1 - dist / 80) * 0.3
        ctx.strokeStyle = `rgba(99, 102, 241, ${alpha})`
        ctx.lineWidth = 0.5
        ctx.beginPath()
        ctx.moveTo(this.x, this.y)
        ctx.lineTo(other.x, other.y)
        ctx.stroke()
      }
    }
  }
  
  // 异步初始化粒子系统避免阻塞
  let particles = []
  
  // 使用 setTimeout 让出主线程
  setTimeout(() => {
    initTargetPositions()
    
    // 检测设备性能并调整粒子数量
    const isMobile = /mobile|android|iphone|ipad/i.test(navigator.userAgent)
    const sampleRate = isMobile ? 10 : 6 // 进一步减少粒子以提升性能
    
    const optimizedPositions = targetPositions.filter((_, index) => index % sampleRate === 0)
    particles = optimizedPositions.map(pos => new Particle(pos))
  }, 0)
  
  // 动画循环
  const animate = () => {
    ctx.fillStyle = 'rgba(10, 15, 30, 0.3)'
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    
    // 更新粒子
    particles.forEach(particle => particle.update())
    
    // 绘制连线（只绘制部分以提升性能）
    if (particles.length > 0) {
      ctx.shadowBlur = 0
      for (let i = 0; i < particles.length; i += 5) {
        for (let j = i + 1; j < Math.min(i + 3, particles.length); j++) {
          particles[i].drawConnection(ctx, particles[j])
        }
      }
    }
    
    // 绘制粒子
    particles.forEach(particle => particle.draw(ctx))
    
    animationId = requestAnimationFrame(animate)
  }
  
  animate()
  
  // 清理
  onUnmounted(() => {
    if (animationId) {
      cancelAnimationFrame(animationId)
    }
    window.removeEventListener('resize', resizeCanvas)
    window.removeEventListener('mousemove', handleMouseMove)
    window.removeEventListener('mouseleave', handleMouseLeave)
  })
})
</script>

<style scoped>
.particle-nebula {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 2;
  opacity: 0.9;
}
</style>

